package cn.zzszxyy.hr.controller;

import cn.zzszxyy.hr.comm.CryptUtil;
import cn.zzszxyy.hr.comm.Global;
import cn.zzszxyy.hr.comm.StringUtil;
import cn.zzszxyy.hr.exception.SystemException;
import cn.zzszxyy.hr.model.DepartmentEntity;
import cn.zzszxyy.hr.model.MenuEntity;
import cn.zzszxyy.hr.model.RoleEntity;
import cn.zzszxyy.hr.model.UserEntity;
import cn.zzszxyy.hr.service.DeptService;
import cn.zzszxyy.hr.service.MenuService;
import cn.zzszxyy.hr.service.RoleService;
import cn.zzszxyy.hr.service.UserService;
import cn.zzszxyy.hr.support.AuthPassport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者:张伟
 * <p>
 * 联系:adamzzww@163.com
 * 时间:2016-11-27
 * 说明:无
 */
@Controller
@RequestMapping(Global.PATH)
public class UserController extends ControllerEx {

    private final String path = "/user";

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private RoleService roleService;

    @AuthPassport
    @RequestMapping(value = path + "/list", method = RequestMethod.GET)
    public String get(HttpServletRequest request, ExtendedModelMap map) {
        Integer pageIndex = getPageIndex(request);
        String userName = request.getParameter("userName");
        map.put("nameList", userService.getAllUserName());
        map.put("page", userService.findByUserName(userName, pageIndex, Global.PAGE_SIZE));
        map.put("pageIndex", pageIndex);
        return Global.DESKTOP + path + "/user-list";
    }

    @RequestMapping(value = path + "/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String loginName = request.getParameter("loginName");
        String userPwd = request.getParameter("userPwd");
        UserEntity user = userService.findByLoginNameAndUserPwd(loginName, userPwd);
        if (user != null) {
            // 用户存在，则:
            // 1. 将用户信息保存在session中，随时读取
            //request.getSession().setAttribute(Global.COOKIE_USER_ID, user.getUserId().toString());
            request.getSession().setAttribute(Global.COOKIE_USER_OBJECT, user);
            //request.getSession().setAttribute(Global.Web.JSP_USER_OBJECT, user);
            Global.JSP_MENU_CONTENT = getNavMenu(request, user.getRole().getRoleId());
            // 2. 将用户id存储在cookie中，便于验证是否登录
            //CookieUtils.setCookie(request, response, Global.Web.COOKIE_USER_ID, user.getUserId().toString(), Global.Web.COOKIE_EXPIRE_TIME);
        } else {
            // 用户不存在，跳转到登录错误页面
            throw new SystemException("用户名或密码错误！");
        }
        return "redirect:" + Global.INDEX_PAGE;
    }

    /**
     * 根据 roleId 动态拼接菜单内容
     *
     * @param request
     * @param roleId
     * @return
     */
    public String getNavMenu(HttpServletRequest request, int roleId) {
        List<MenuEntity> menuList = menuService.findMenusByRoleId(roleId);
        List<MenuEntity> topLevMenu = new ArrayList<>();
        for (MenuEntity menu : menuList) {
            if (0 == menu.getpMenuId()) {
                topLevMenu.add(menu);
            }
        }
        String liBeg = "<li>";
        String liEnd = "</li>";
        String ulBeg = "<ul class=\"dropdown-menu\">";
        String ulEnd = "</ul>";
        String ulContent = "";
        String liContent = "";
        String topLevMenuStr = "";
        String secLevMenuStr = "";
        String menuContent = "";
        for (MenuEntity topMenu : topLevMenu) {
            topLevMenuStr = "<a class=\"dropdown-toggle\" data-toggle=\"dropdown\">" + topMenu.getMenuName() + "<span\n" +
                    "class=\"caret\"></span></a>";
            for (MenuEntity entity : menuList) {
                if (0 != entity.getpMenuId()) {
                    if (entity.getpMenuId() == topMenu.getMenuId()) {
                        secLevMenuStr = secLevMenuStr + "<li><a href='" + request.getContextPath() + entity.getMenuUrl() + "'>" + entity.getMenuName() + "</a></li>";
                    }
                }
            }
            ulContent = ulBeg + secLevMenuStr + ulEnd;
            liContent = liBeg + topLevMenuStr + ulContent + liEnd;
            secLevMenuStr = "";
            menuContent = menuContent + liContent;
        }
        return menuContent;
    }

    @RequestMapping(value = path + "/{id}", method = RequestMethod.GET)
    public String get(@PathVariable int id, ExtendedModelMap map) {
        UserEntity userEntity = userService.findOne(id);
        map.put("userEntity", userEntity);
        List<DepartmentEntity> deptList = deptService.findAll();
        map.put("deptList", deptList);
        List<RoleEntity> roleList = roleService.findAll();
        map.put("roleList", roleList);

        return Global.DESKTOP + path + "/user-edit";
    }


    @RequestMapping(value = path + "/{id}/reset", method = RequestMethod.GET)
    public String reset(@PathVariable int id) {
        userService.restUserPwdFor(id);
        return "redirect:" + Global.PATH + path + "/list";
    }

    @ResponseBody
    @RequestMapping(value = path, method = RequestMethod.POST)
    public String post(HttpServletRequest request, UserEntity userEntity) {
        UserEntity loginUser = (UserEntity) request.getSession().getAttribute(Global.COOKIE_USER_OBJECT);

        if (null == userEntity.getUserId()) {
            userEntity.setCreator(loginUser.getLoginName());
            userEntity.setCreateTime(new Date());
            userEntity.setUserPwd(CryptUtil.getInstance().defalutEncrypt(Global.DEFALUT_PWD));
        } else {
            UserEntity dbEntity = userService.findOne(userEntity.getUserId());
            userEntity.setCreator(dbEntity.getCreator());
            userEntity.setCreateTime(dbEntity.getCreateTime());
            userEntity.setUpdater(loginUser.getLoginName());
            userEntity.setUpdateTime(new Date());
            // 原有密码保持
            userEntity.setUserPwd(dbEntity.getUserPwd());
        }
        if (userService.save(userEntity) != null) {
            return Global.RE_SUCCESS;
        } else {
            return Global.RE_ERROR;
        }
    }

    @RequestMapping(value = path + "/add", method = RequestMethod.GET)
    public String add(ExtendedModelMap map) {
        List<DepartmentEntity> deptList = deptService.findAll();
        List<RoleEntity> roleList = roleService.findAll();
        map.put("deptList", deptList);
        map.put("roleList", roleList);

        return Global.DESKTOP + path + "/user-add";
    }

    @RequestMapping(value = path + "/toLogin", method = RequestMethod.GET)
    public String toLogin() {
//        String defaultPwd = CryptUtil.getInstance().defalutEncrypt(Global.DEFALUT_PWD);
//        System.out.println(defaultPwd);
        return Global.DESKTOP + path + "/login";
    }

    @RequestMapping(value = path + "/logOut", method = RequestMethod.GET)
    public String logOut(HttpServletRequest request) {
        request.getSession().removeAttribute(Global.COOKIE_USER_OBJECT);
        return Global.DESKTOP + path + "/login";
    }

    @ResponseBody
    @RequestMapping(value = path + "/validate", method = RequestMethod.GET)
    public String validate(HttpServletRequest request) {
        String loginName = request.getParameter("loginName");
        String flag = Global.RE_ERROR;
        if (!StringUtil.isEmpty(loginName)) {
            if ((userService.isExistByLoginName(loginName))) {
                //如果存在此用户名，则返回true
                flag = Global.RE_SUCCESS;
            }
        }
        return flag;
    }

    @RequestMapping(value = path + "/toChangePwd", method = RequestMethod.GET)
    public String toChangePwd() {

        return Global.DESKTOP + path + "/change-pwd";
    }

    @RequestMapping(value = path + "/changePwd", method = RequestMethod.POST)
    public String changePwd(HttpServletRequest request, UserEntity userEntity) {
        UserEntity loginUser = (UserEntity) request.getSession().getAttribute(Global.COOKIE_USER_OBJECT);
        String Pwd = request.getParameter("userPwd");
        userService.changeUserPwdFor(Pwd, loginUser.getUserId());
        return Global.DESKTOP + path + "/change-pwd";
    }
}
